package com.xt.base.action;

import java.util.Stack;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.AroundInterceptor;
import com.xt.base.acegi.AcegiUtils;
import com.xt.base.model.system.User;
import com.xt.base.service.LoginService;

public class UserInfoInterceptor extends AroundInterceptor {

	private static final long serialVersionUID = 5762618059905446642L;

	private static final Logger LOG = Logger
			.getLogger(UserInfoInterceptor.class);

	LoginService loginService = null;

	public UserInfoInterceptor() {
		super();
	}

	protected void after(ActionInvocation arg0, String arg1) throws Exception {
		LOG.info(" after execute action ");
	}

	protected void before(ActionInvocation arg0) throws Exception {
		LOG.info(" before execute action ");
		HttpSession session = ServletActionContext.getRequest().getSession();
		Object currentUser = session
				.getAttribute(BaseAction.SESSIONCURRENTUSER);
		String loginName = AcegiUtils.getUsername();
		if (StringUtils.isEmpty(loginName)) {
			throw new Exception("认证数据没有找到!!!");
		}
		if (currentUser == null
				|| (!((User) currentUser).getUsername().equalsIgnoreCase(
						loginName))) {
			User user = loginService.reLoadUserInfo(loginName, AcegiUtils.getPassword());
			user.initialize();
			session.setAttribute(
					BaseAction.SESSIONCURRENTUSER,
					user);
			Stack sessionStack = (Stack) session.getAttribute("sessionStack");
			if (sessionStack == null) {
				Stack s = new Stack();
				session.setAttribute("sessionStack", s);
			}
		}
	}

	public void setUserManager(LoginService loginService) {
		this.loginService = loginService;
	}

}
